use async_trait::async_trait;
use serde_json::{Map, Value};
use shq_common::prelude::{empl::EmployeeCache, json_value_to_string, Callback};

pub struct RoleCallback;
impl RoleCallback{
    pub fn new() -> RoleCallback{
        RoleCallback{}
    }
}

#[async_trait]
impl Callback for RoleCallback{
    async fn before_insert(
        &mut self,
        map_val: Map<String,Value>,
        tx: &mut sqlx::Transaction<'_,sqlx::MySql>,
    )-> anyhow::Result<Map<String,Value>>{
        let name = map_val
        .get("name")
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow::anyhow!("name字段没有找到"))?;
        if name.is_empty(){
            return Err(anyhow::anyhow!("name字段不能为空"));
        }
        let sql = "SELECT COUNT(*) as count FROM sys_role WHERE name = ?";
        let count: i64 = sqlx::query_scalar(sql)
            .bind(name)
            .fetch_one(&mut **tx)
            .await
            .map_err(|e| anyhow::anyhow!("查询name是否存在失败: {}", e))?;
        if count > 0 {
            return Err(anyhow::anyhow!("角色名:{name}已存在"));
        }
        Ok(map_val)
    }
}